package com.lin.ovc.pomodoro.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lin.ovc.pomodoro.entity.User;
import com.lin.ovc.pomodoro.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class UserAuthService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 判断用户名是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name",username);
        User user = userMapper.selectOne(wrapper);

        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        // 从数据库中获取的密码 atguigu 的密文
        String pwd = user.getPassword();

        // 第三个参数表示权限
        return new org.springframework.security.core.userdetails.User(username, pwd, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
